package ie.ucc.cs.anggao.finalproject.client.ui.mainpanel.infopane.PageableFlextTable;

import com.google.gwt.user.client.ui.HasHorizontalAlignment;

public abstract class PageableFlexTable extends
		BaseFlexTable implements CanPage, PagerListener {

	private static final int DEFAULT_PAGE_SIZE = 6;
	
	private Pager pager = null;
	private int pageSize = DEFAULT_PAGE_SIZE;
	
	public abstract Object[][] getData(int startIndex);
	
	public abstract boolean isLastPage(int index);
	
	public PageableFlexTable(int pageSize) {
		super();
		this.pageSize = pageSize;
		createDataRows();
		populateDataRows(getData(DATA_INDEX_ZERO));
		applyDataRowStyles();
		addPager();
	}
	
	private void createDataRows() {
		for (int row = FIRST_DATA_ROW; row < pageSize; ++row)
			insertRow(row);
	}
	
	private void populateDataRows(Object[][] data) {
		for (int row = FIRST_DATA_ROW; row <= pageSize; ++row) {
			Object[] rowData = data[row-1];
			for (int cell = 0; cell < rowData.length; ++cell)
				addCell(row, cell, rowData[cell]);
		}
	}
	
	private void addPager() {
		pager = new Pager(this);
		pager.addPagerListener(this);
		
		int row = getRowCount();
		setWidget(row, FIRST_COLUMN, pager);
		
		getRowFormatter().addStyleName(row,"gwtsolutions-EasyFlexTable-PagerRow");
		
		getCellFormatter().setHorizontalAlignment(row,FIRST_COLUMN, HasHorizontalAlignment.ALIGN_RIGHT);
		
		((FlexCellFormatter) getCellFormatter()).setColSpan(row,FIRST_COLUMN, getCellCount(FIRST_DATA_ROW));
	}
	
	public void onPage(SourcesPagerEvents sender, int index) {
		clearDataRows();	
		populateDataRows(getData(index));
	}
	
	private void clearDataRows() {
		for (int row = FIRST_DATA_ROW; row <= pageSize; ++row) {
			for (int cell = 0; cell < getCellCount(row); ++cell) {
				clearCell(row, cell);
			}
		}
	}
	
	public int getPageSize() {
		return pageSize;
	}
}
